package fun.yyds.service.sys.impl;

import fun.yyds.service.sys.UdpService;
import fun.yyds.utils.LogUtil;
import org.springframework.integration.ip.udp.MulticastSendingMessageHandler;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.charset.StandardCharsets;

/**
 * @description: SysServiceImpl
 * @author: Chensn
 * @time: 2024/10/31
 */
@Service
public class UdpServiceImpl implements UdpService {
    @Resource
    private MulticastSendingMessageHandler multicastSender;

    private MulticastSocket multicastSocket;

    public void send(String json) {
        // 手动转换为字节数组并发送
        byte[] payload = json.getBytes(StandardCharsets.UTF_8);
        multicastSender.handleMessage(
                MessageBuilder.withPayload(payload).build()
        );
        System.out.println("组播发送消息：" + json);
        LogUtil.jsonLog("XTYW", "系统日志", "info", "监控模块",
                json, "成功", "192.168.2.1", "");
    }


    public void send2(String json) throws IOException {
        byte[] bytes = json.getBytes();
        multicastSocket = new MulticastSocket();
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("224.1.1.100"), 12345);
        multicastSocket.send(datagramPacket);
    }


}
